Directus 有提供 javascript 工具方便整合,先在先前的 NextJS 專案中安裝
yarn add @directus/sdk
開一個新頁面測試,順便套個 Tanstack Query。
"use client";
import { createDirectus, readItems, rest } from "@directus/sdk";
import { useQuery } from "@tanstack/react-query";
interface Post {
id: number;
title: string;
content: string;
}
interface Schema {
posts: Post[];
}
// Client with REST support
const client = createDirectus<Schema>("http://127.0.0.1:8055").with(rest());
const Page = () => {
const { isPending, error, data } = useQuery({
queryKey: ["directus-posts"],
queryFn: () => client.request(readItems("posts")),
});
return (
<>
<h1>{"Post"}</h1>
</>
);
};
export default Page;
到這邊出現了 CORS 錯誤,需要設定 Directus 的 CORS 設定才行。
之前是簡單用 docker hub 啟動 Directus,現在為了進行詳細的設定用 docker-compose 比較方便。順便開個資料庫以確保每次重開容器時資料不會消失。
另開一個資料夾後在裡面新建 docker-compose.yml
順便弄個 .env
# docker-compose.yml
version: "3"
services:
database:
image: postgis/postgis:13-master
# Required when running on platform other than amd64, like Apple M1/M2:
platform: linux/amd64
volumes:
- ./data/database:/var/lib/postgresql/data
environment:
POSTGRES_USER: "directus"
POSTGRES_PASSWORD: "directus"
POSTGRES_DB: "directus"
healthcheck:
test: ["CMD", "pg_isready", "--host=localhost", "--username=directus"]
interval: 10s
timeout: 5s
retries: 5
# start_interval: 5s
start_period: 30s
cache:
image: redis:6
healthcheck:
test: ["CMD-SHELL", "[ $$(redis-cli ping) = 'PONG' ]"]
interval: 10s
timeout: 5s
retries: 5
# start_interval: 5s
start_period: 30s
directus:
image: directus/directus:11.1.0
ports:
- 8055:8055
volumes:
- ./uploads:/directus/uploads
- ./extensions:/directus/extensions
depends_on:
database:
condition: service_healthy
cache:
condition: service_healthy
env_file:
- .env
# .env
SECRET="replace-with-secure-random-value"
DB_CLIENT="pg"
DB_HOST="database"
DB_PORT="5432"
DB_DATABASE="directus"
DB_USER="directus"
DB_PASSWORD="directus"
CACHE_ENABLED="true"
CACHE_AUTO_PURGE="true"
CACHE_STORE="redis"
REDIS="redis://cache:6379"
ADMIN_EMAIL="admin@example.com"
ADMIN_PASSWORD="d1r3ctu5"
CORS_ENABLED="true"
CORS_ORIGIN="http://localhost:3000"
CORS_METHODS="GET, POST, PUT, PATCH, DELETE, OPTIONS"
CORS_HEADERS="Authorization, Content-Type, X-Requested-With"
最底下進行 CORS 設定,對 NextJS 開放。
docker-compose up
後等全部架設好後,得重新建好 Collection 到 Item ,再來嘗試連上 API。